﻿using System;
using System.Configuration;
using System.Linq;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using Medianamik.Core;
using Medianamik.Core.Configuration;
using Medianamik.Globalization;
using Telerik.Web.UI;
using Telerik.Web.UI.Editor.DialogControls;
using System.Globalization;

namespace Medianamik.UI.Controls
{
    public abstract class BaseImagePicker : BaseMedianamikControl, IScriptControl
    {
        private const string SPACER = "/medianamik/images/spacer.gif";
        private RadDialogOpener opener;
        private Panel divFile;
        //Icône d'ouverture du dialogue
        private Image imgButton;
        private Image imgDelete;
        private TextBox hiddenTextBox;
        private FileManagerDialogParameters imageManagerParameters;
        private DialogDefinition imageManager;
        private ImageManagerDialogParameters imageEditorParameters;
        private DialogDefinition imageEditor;

        protected abstract HashSet<string> ImagePaths { get; }

        public virtual void AddPath(string path)
        {
            ImagePaths.Add(path);
        }

        public virtual void RemovePath(string path)
        {
            ImagePaths.Remove(path);
        }

        protected override bool WrapContentInParagraph
        {
            get
            {
                return false;
            }
        }

        protected override void CreateControlHierarchy(bool pUseDataSource)
        {

            opener = new RadDialogOpener();
            divFile = new Panel();
            hiddenTextBox = new TextBox();
            imageManagerParameters = new ImageManagerDialogParameters();
            imageEditorParameters = new ImageManagerDialogParameters();
            imgButton = new Image { ID = "OpenButton"};
            imgDelete = new Image { ID = "DeleteButton"};
            
            Controls.Add(divFile);
            Controls.Add(opener);
            Controls.Add(hiddenTextBox);
            Controls.Add(new LiteralControl("<p>")); 
            Controls.Add(imgButton);
            Controls.Add(new LiteralControl("&nbsp;&nbsp;"));
            Controls.Add(imgDelete);
            Controls.Add(new LiteralControl("</p>"));

            imageManagerParameters.ViewPaths = ImagePaths.ToArray();
            imageManagerParameters.UploadPaths = ImagePaths.ToArray();
            imageManagerParameters.DeletePaths = ImagePaths.ToArray();
            imageManagerParameters.MaxUploadFileSize = 5000000;
            imageManagerParameters.SearchPatterns = new[] { "*.jpg", "*.jpeg", "*.gif", "*.png" };
            imageManagerParameters["Language"] = CultureInfo.CurrentCulture.Name ;
            imageManager = new DialogDefinition(typeof(ImageManagerDialog), imageManagerParameters)
                               {
                                   Width = Unit.Pixel(((MedianamikConfigSection)ConfigurationManager.GetSection(ConfigurationSectionName.MEDIANAMIK)).ImagePickerManagerWidth),
                                   Height = Unit.Pixel(((MedianamikConfigSection)ConfigurationManager.GetSection(ConfigurationSectionName.MEDIANAMIK)).ImagePickerManagerHeight)
                               };

            imageEditorParameters.ViewPaths = ImagePaths.ToArray();
            imageEditorParameters.UploadPaths = ImagePaths.ToArray();
            imageEditorParameters.DeletePaths = ImagePaths.ToArray();
            imageEditorParameters.MaxUploadFileSize = 5000000;
            imageEditorParameters["Language"] = CultureInfo.CurrentCulture.Name;
            
            imageEditor = new DialogDefinition(typeof(ImageEditorDialog), imageEditorParameters)
                  {
                      Width = Unit.Pixel(((MedianamikConfigSection)ConfigurationManager.GetSection(ConfigurationSectionName.MEDIANAMIK)).ImagePickerEditorWidth),
                      Height = Unit.Pixel(((MedianamikConfigSection)ConfigurationManager.GetSection(ConfigurationSectionName.MEDIANAMIK)).ImagePickerEditorHeight)
                  };

            imgButton.ImageUrl = "/medianamik/images/icones/ico_repertoire.gif";
            imgButton.AlternateText = Translator.Translate("medianamik_controls", "open_imagepicker");
                       
            imgDelete.ImageUrl = "/medianamik/images/Icones/Ico_Supprimer.gif";
            imgDelete.AlternateText = Translator.Translate("medianamik_controls", "delete_imagepicker_content");
            
            opener.ID = "opener";
            opener.EnableEmbeddedSkins = Skins.DEFAULT_USE_EMBEDDED_SKIN;
            opener.Skin = Skins.DEFAULT_SKIN;
            opener.DialogDefinitions.Add("ImageManager", imageManager);
            opener.DialogDefinitions.Add("ImageEditor", imageEditor);

            hiddenTextBox.ID = ControlToValidateId;
            hiddenTextBox.Attributes.Add("style", "DISPLAY: none; ");

            divFile.ID = "openerImage";
            divFile.BorderStyle = BorderStyle.Solid;
            divFile.BorderWidth = Unit.Pixel(1);
            divFile.Style.Add("background-repeat", "no-repeat");
            divFile.Style.Add("background-position", "top left");
            divFile.Style.Add("margin-bottom", "5px");
            divFile.Style.Add("border-color", "#848484 #e7e7e7 #e7e7e7 #848484");

            imageManager.ClientCallbackFunction = String.Format("Function.createDelegate($find('{0}'), $find('{0}').imageManagerCallBack)", ClientID);
            imgButton.Attributes.Add("onclick", string.Format("$find('{0}').get_opener().open('ImageManager', {{CssClasses: []}});return false;", ClientID));
            imgDelete.Attributes.Add("onclick", string.Format("$find('{0}').reset();return false;", ClientID ));   

            if (pUseDataSource)
            {
              hiddenTextBox.Text = (DataSource == null) ? String.Empty : DataSource.ToString();

                //Ne pas mettre String.Empty - cause le rechargement de la page //TODO - Revoir défaut
                var dataSource = DataSource as string;
                divFile.BackImageUrl = string.IsNullOrEmpty(dataSource) ? SPACER : dataSource;
                
                divFile.Width = ControlInfo.Width.HasValue
                              ? ControlInfo.Width.Value
                              : WIDTH;

                divFile.Height = ControlInfo.Height.HasValue
                    ? ControlInfo.Height.Value
                    : HEIGHT;
            }

        }

        public override Type TypeOfValue
        {
            get { return typeof(string); }
        }

        public override object GetValue()
        {
            EnsureChildControls();
            return hiddenTextBox.Text;
        }
        public override void SetValue(object value)
        {
            EnsureChildControls();
            divFile.BackImageUrl = value == null ? null : value.ToString();
            hiddenTextBox.Text = value == null ? null : value.ToString();
        }

        protected override void OnPreRender(EventArgs e)
        {
            if (!DesignMode)
            {
                // Test for ScriptManager and register if it exists
                var sm = ScriptManager.GetCurrent(Page);
                if (sm == null)
                {
                    throw new Exception("A ScriptManager control must exist on the current page.");
                }
                sm.RegisterScriptControl(this);
            }
            base.OnPreRender(e);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            if (!DesignMode)
            {
                var sm = ScriptManager.GetCurrent(Page);
                if (sm != null) sm.RegisterScriptDescriptors(this);
            }
            base.Render(writer);
        }

        public IEnumerable<ScriptDescriptor> GetScriptDescriptors()
        {
            var descriptor = new ScriptControlDescriptor("Medianamik.ImagePicker", ClientID);
            descriptor.AddElementProperty("imageContainer", divFile.ClientID);
            descriptor.AddElementProperty("hiddenPathField", hiddenTextBox.ClientID);
            descriptor.AddComponentProperty("opener", opener.ClientID);
            descriptor.AddProperty("spacer", SPACER);
            return new ScriptDescriptor[] { descriptor };
        }

        public IEnumerable<ScriptReference> GetScriptReferences()
        {
            var path = Core.Sugar.Resources.GetWebResourceUrl("Scripts.ImagePicker.js", Page, typeof(BaseImagePicker), typeof(BaseImagePicker).Assembly);
            var reference = new ScriptReference(path);
            return new[] { reference };
        }
    }
}